//
//  LoginViewController.swift
//  SinaBlog
//
//  Created by 李超 on 16/3/21.
//  Copyright © 2016年 lichao. All rights reserved.
//

import UIKit

import SVProgressHUD

extension LoginViewController :UIWebViewDelegate{
    //开始加载页面
    func webViewDidStartLoad(webView: UIWebView) {
     
        SVProgressHUD.showWithStatus("正在加载页面", maskType: SVProgressHUDMaskType.Black)
        
    }
    //完成加载页面
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    //授权回调处理,根据request来进行判断是否进行加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
       // print(request)
        let urlString = request.URL!.absoluteString
        
        if !urlString.hasPrefix(redirect_uri){
            return true
        }
        
        //如果有参数
        if let query = request.URL?.query{
            //将参数转变成为字符串对象，方便进行判断并截取
            let nsquery = query as NSString
            let codeString = "code="
            //如果授权则进行登录，没有授权则进行dismiss控制器
            if nsquery.hasPrefix(codeString){
              //获取code，并加载accessToken
                let code = nsquery.substringFromIndex(codeString.characters.count)
                //利用单例进行管理用户登录的相关数据
                CZUserAccountTool.shareInstance.loadAccessToken(code, completion: { (error) -> () in
                    if error == nil {
                       print("保存成功")
                       self.cancleLogin()
                        //跳转到欢迎界面
                        AppDelegate.outSwitchViewController(false)
                        
                    }else{
                      //加载失败
                        SVProgressHUD.showErrorWithStatus("您的网络不给力", maskType: SVProgressHUDMaskType.Black)
                        
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                            self.cancleLogin()
                        })
                        
                        
                    }
                    
                    
                    
                })
                
            }
        }
        
        
        return false
    }
    
}

class LoginViewController: UIViewController {

    override func loadView() {
        //设置跟视图为webview
        view = webView
        webView.delegate = self
        view.backgroundColor = UIColor.whiteColor()
        addNavigationItems()
    }
    
    override func viewDidLoad() {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        //开始加载数据
        webView.loadRequest(request)
        
    }
        //添加左右按钮
    func addNavigationItems(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFullFill")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancleLogin")
        
    }
    //自动填充
    func autoFullFill(){
        let js = "document.getElementById('userId').value='lijunlin_1102@sina.com';document.getElementById('passwd').value='lijunlin1987'"
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    //取消登陆
    func cancleLogin(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    //懒加载
    private lazy var webView:UIWebView = UIWebView()
    
}
